import Toast from 'tdesign-miniprogram/toast/index';
import Log from '../../utils/log';
import commondUtil from '../../utils/commondUtil';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    signDetail: [],
    pageClientName: '',
    loadingFlag: false,
    scrollTop: 0,

    socketTaskObj: null,
    socketConectFlag: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel();
    if (typeof eventChannel?.on === 'function') {
      // 监听'delivery'事件，并获取数据包
      eventChannel.on('delivery', (param) => {
        const pageClientName = param?.pageClientName || '';
        let signDetail = param?.signDetail || [];
        if (commondUtil.isEmpty(signDetail) && commondUtil.isBlank(pageClientName)) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '签到详情为空！',
            theme: 'warning',
            direction: 'column',
          });
          wx.navigateBack();
          return;
        }

        signDetail = this.formatDetailMsg(signDetail);
        this.setData({
          signDetail: signDetail,
          pageClientName: pageClientName
        }, () => {
          this.scrollToBottom();
        });

        if (commondUtil.isNotBlank(pageClientName)) {
          this.connectWebsocket();
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (commondUtil.isNotEmpty(this.data.socketTaskObj)) {
      this.data.socketTaskObj.close({
        success: function (res) {
          Log.infoAll(res, '签到详情页面销毁：关闭websocket');
        },
        fail: function (e) {
          Log.errorAll('签到详情页面销毁：关闭websocket失败!', e);
        }
      });

      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel != null) {
        eventChannel.emit('refreshSignRecord');
      }
    }
  },

  formatDetailMsg(list) {
    if (commondUtil.isEmpty(list)) {
      return [];
    }
    const reg = /^\[.*?\]\s*\[.*?\]\s*([\s\S]*)/;
    list.forEach(item => {
      const match = item.msg?.match(reg);
      if (match && match[1]) {
        item.title = match[1];
      }
    });
    return list;
  },

  connectWebsocket() {
    // 'testClient-page-28-wx-' + commondUtil.uuid();
    const clientName = this.data.pageClientName;
    const token = wx.getStorageSync('token');
    if (commondUtil.isBlank(clientName) || commondUtil.isBlank(token)) {
      return;
    }
    const g = this;
    const socketTaskObj = wx.connectSocket({
      url: 'wss://www.demon.autos/demon-auto/ws/sign?clientName=' + clientName,
      header: {
        'content-type': 'application/json',
        token
      },
      success: function (res) {
        Log.infoAll("成功连接服务端websocket", res);
        g.setData({
          socketConectFlag: true
        });
        Toast({
          context: this,
          selector: '#t-toast',
          message: '已连接服务端',
          theme: 'success',
          direction: 'column',
        });
      },
      fail: function (e) {
        Log.errorAll("连接服务端websocket异常！", e);
        g.setData({
          loadingFlag: false
        });
        Toast({
          context: this,
          selector: '#t-toast',
          message: '连接服务端异常！',
          theme: 'error',
          direction: 'column',
        });
      }
    });

    if (commondUtil.isEmpty(socketTaskObj)) {
      return;
    }

    socketTaskObj.onOpen((header) => {
      g.setData({
        loadingFlag: true
      });
    });
    socketTaskObj.onMessage((data) => {
      let msgData = data.data;
      try {
        msgData = JSON.parse(msgData);
      } catch (e) {
        Log.errorAll("解析服务端消息异常！", data, e);
        return;
      }
      if (msgData.type !== "sign_process") {
        Log.errorAll("消息类型不是签到过程：", msgData);
        return;
      }
      let detailData = msgData.data;
      if (commondUtil.isEmpty(detailData)) {
        Log.errorAll("签到过程数据为空！", detailData);
        return;
      }

      try {
        detailData = JSON.parse(detailData);
      } catch (e) {
        Log.errorAll("解析签到过程数据异常！", data, e);
        return;
      }

      this.setData({
        signDetail: this.formatDetailMsg(detailData)
      }, () => {
        this.scrollToBottom();
      });
      if (detailData[detailData.length - 1].msg.includes("已结束运行")) {
        this.setData({
          loadingFlag: false
        });
      }
    });
    socketTaskObj.onClose((code, reason) => {
      g.setData({
        loadingFlag: false,
        socketTaskObj: null
      });
    });
    this.setData({
      socketTaskObj: socketTaskObj
    });
  },

  /**
   * 滚动到页面底部
   */
  scrollToBottom() {
    wx.createSelectorQuery().select('#signDetailView').boundingClientRect((rect) => {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      this.setData({
        scrollTop: rect.height - this.data.scrollTop
      });
    }).exec();
  }

})